#include <chrono>
#include <ctime>
#include <crow.h>
#include <crow/mustache.h>
#include <iostream>
#include <vector>
#include <map>



int main() {
    crow::SimpleApp app;

/*
    // Serve static files - Manual static file serving
    CROW_ROUTE(app, "/static/<path>")
    ([](const crow::request& req, crow::response& res, std::string path) {
        // Prevent directory traversal
        if (path.find("..") != std::string::npos) {
            res.code = 403;
            res.end("Forbidden");
            return;
        }

        // Build the full file path
        std::string file_path = "static/" + path;
        
        // Serve the file
        res.set_static_file_info(file_path);
        res.end();
    });
*/
  CROW_ROUTE(app, "/")
  ([]() {
    return "<!DOCTYPE html><html><body><h1>Hello World!</h1></body></html>";
  });

  CROW_ROUTE(app, "/time")
  ([]() {
    std::chrono::system_clock::time_point now =
        std::chrono::system_clock::now();
    time_t tt = std::chrono::system_clock::to_time_t(now);
    // tm utc_tm = *gmtime(&tt);
    tm local_tm = *localtime(&tt);

    auto page = crow::mustache::load("time.html");

    crow::mustache::context ctx({{"year", local_tm.tm_year + 1900},
                                 {"month", local_tm.tm_mon + 1},
                                 {"day", local_tm.tm_mday},
                                 {"hour", local_tm.tm_hour},
                                 {"min", local_tm.tm_min},
                                 {"sec", local_tm.tm_sec}});
    return page.render(ctx);
  });

  CROW_ROUTE(app, "/<string>")
  ([](std::string name) {
    auto page = crow::mustache::load("hello.html");
    crow::mustache::context ctx({{"person", name}});
    return page.render(ctx);
  });

    // Custom 404 handler
    CROW_CATCHALL_ROUTE(app)([](){
        crow::mustache::context ctx;
        ctx["title"] = "Page Not Found";
        ctx["message"] = "The page you're looking for doesn't exist.";
        auto page = crow::mustache::load("404.html");
        return page.render();
    });

    std::cout << "Server running on http://127.0.0.1:8080\n";
    app.port(8080).multithreaded().run();
}
